const { Orders } = require('../models/orders');
const { Admins } = require('../models/admins');
const { Cars } = require('../models/cars');
const { Remarks } = require('../models/remarks');
const { Users } = require('../models/users');

const findByPaginationHandler = async function (type, msg) {
    console.log("type", type);
    // console.log("data", msg)
    let Collection;
    let data;
    let totalCount;
    const { pageSize, pageNumber, conditions = { type: '' } } = msg;


    switch (type) {
        case "orders": Collection = Orders; break;
        case "admins": Collection = Admins; break;
        case "cars": Collection = Cars; break;
        case "remarks": Collection = Remarks; break;
        case "users": Collection = Users; break;
    }
    totalCount = await Collection.countDocuments();//数据总数

    console.log("conditions", conditions.type)

    //如果是orders的话
    if (type === "orders") {
        let totalArray = await Orders.find({ status: { $ne: 'delete' } });
        // console.log(totalArray.length)
        totalCount = totalArray.length;
    }

    if (conditions.type !== "" && type == "orders") {
        let totalArr = await Orders.find({ status: conditions.type });
        // console.log(totalArr.length)
        totalCount = totalArr.length;
    }

    const num = (pageNumber - 1) * pageSize;//上一页到第一页的数据总数
    if (totalCount <= num) {
        return [];//表示当前页没有数据 
    }
    //获取分页数据
    switch (type) {
        case 'orders':
            const { type, ownerId, userId } = conditions;
            if (!ownerId && !userId) {
                data = await Collection.find({
                    //[]代表字段名称
                    ["status"]: {
                        $regex: type,
                        $options: '$i',
                        $ne: 'delete'
                    },
                }).limit(pageSize).skip((pageNumber - 1) * pageSize)
                    .populate("carId").populate('ownerId').populate('userId');
            }

    }
    // console.log("data", data);
    console.log("length 长度", data.length);
    return {
        data: data,
        totalCount,
    };
}


module.exports = findByPaginationHandler;